package info.hexin.dao.core;

import info.hexin.dao.callback.ConnectionCallback;
import info.hexin.log.Log;
import info.hexin.log.Logs;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

public class BaseDao {
    private static Log log = Logs.get();

    private DataSource dataSource;

    public BaseDao(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        if (this.dataSource != null) {
            this.dataSource = dataSource;
            if (log.isErrorEnabled()) {
                log.error("a runing DataSource will be replaced");
            }
        }
    }

    void exec(ConnectionCallback callback) {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            callback.doInConnection(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
